package org.csu.mypetstore.controller;

import org.csu.mypetstore.tool.MailTool;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.Random;

@Controller

@RequestMapping("/email")
public class UserController {


    //页面控制



    @GetMapping({"/login"})
    public String login(){
        return "login";
    }




    //验证码
    @ResponseBody
    @RequestMapping("/getCode")

    public boolean getCode(String email , HttpServletRequest request){
        //随机生成一个验证码
        Integer code=new Random().nextInt(500);
        request.getSession().setAttribute("code",code.toString());
        request.getSession().setAttribute("email",email);
        new Thread(
                new Runnable() {
                    @Override
                    public void run() {
                        MailTool.send(email,code);
                    }
                }
        ).start();
        return true;
    }

    //登陆
    @ResponseBody
    @RequestMapping("/tologin")
    public String tologin(String email ,String code,HttpServletRequest request){
        String emailAddress = (String) request.getSession().getAttribute("email");
        String codeId = (String) request.getSession().getAttribute("code");
        System.out.println(codeId);
        System.out.println(code);
        if (email.equals(emailAddress) && code.equals(codeId)){
            return "account/login";
        }else {
            return "account/login";
        }
    }


}
